//
//  ChatTableView.m
//  供销宝
//
//  Created by poweruser on 2017/5/17.
//  Copyright © 2017年 Stone.Sun. All rights reserved.
//

#import "ChatTableView.h"
#import "ChatTableViewVoiceCell.h"
#import "NSMutableArray+InvalidObject.h"
#import "ChatMessage.h"

@interface ChatTableView ()

@property (nonatomic,strong) NSMutableArray *heightArray;

@property (nonatomic,strong) NSMutableArray *voiceArray;

@property (nonatomic,strong) UIActivityIndicatorView *activity;

@end

@implementation ChatTableView

- (NSMutableArray *)heightArray {
    
    if(!_heightArray) {
        _heightArray = [NSMutableArray array];
    }
    return _heightArray;
}

- (NSMutableArray *)voiceArray {
    
    if(!_voiceArray) {
        _voiceArray = [NSMutableArray array];
    }
    return _voiceArray;
}

- (UIActivityIndicatorView *)activity {
    if(!_activity) {
        _activity = [[UIActivityIndicatorView alloc]initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width/2, -15, 15, 15)];
        _activity.activityIndicatorViewStyle = UIActivityIndicatorViewStyleGray;
        [self addSubview:_activity];
    }
    return _activity;
}

- (NSString *)returnFriendPic {
    return self.rcChat.friendLogo;
}

- (NSString *)returnNickName {
    return self.rcChat.friendName;
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.results.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CGFloat height;
    if(self.heightArray.count>indexPath.row) {
        //有缓存，则取高度
        height = [self.heightArray[indexPath.row] floatValue];
    }else {
        //无缓存,计算高度,加入数据组
        
        height =[ChatBaseTableViewCell cellHeightWithModel:self.results[indexPath.row]];
        [self.heightArray addObject:[NSNumber numberWithFloat:height]];
    }
    return height;
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    //复用机制原因，滑出屏时，动画停止了
    if(((ChatTableViewVoiceCell *)cell).voiceAnimationImageView.tag == indexPath.row) {
        if([cell isKindOfClass:[ChatTableViewVoiceCell class]]) {
            if([((ChatTableViewVoiceCell *)cell) player].isPlaying) {
                [((ChatTableViewVoiceCell *)cell) startVoiceAnimation];
            }else {
                [((ChatTableViewVoiceCell *)cell) stopVoiceAnimation];
            }
        }
    }
}

- (UITableViewCell *)tableView:(ChatTableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ChatMessage *currentModel = self.results[indexPath.row];
    
    ChatBaseTableViewCell *cell = (ChatBaseTableViewCell *)[ChatBaseTableViewCell cellWithTableView:tableView messageModel:currentModel];
    
    [cell loadUserPic:[self returnFriendPic] ChatMdl:currentModel];
    [cell setChatMdl:currentModel];
    
    cell.selectVoiceBlock = ^(NSIndexPath *index){
        
    };
    
    cell.removeChatInfoBlock=^(ChatMessage *chatMdl) {
        
        
    };
    
#warning 是不是需要改变
    //只有当图片url  存在时 代表这是一个图片cell 时才实现block
    cell.imageClickBlock = ^(){
        !self.imageClickBlock?:self.imageClickBlock(currentModel);
    };
    
    return cell;
}




-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    !self.scrollWillBeginDragging?:self.scrollWillBeginDragging();
}

//判断是否显示菊花
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {

    if([self.chatProtocol isShowActivityView:self.results.count] && scrollView.contentOffset.y<0) {
        
        [self.activity startAnimating];
        self.activity.hidden = NO;
        self.contentInset = UIEdgeInsetsMake(30, 0, 0, 0);
    }
}

//获取分页数据
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    if([self.chatProtocol isShowActivityView:self.results.count] && scrollView.contentOffset.y<0) {
        //下拉获取数据源
        [self applyForDataSource];
    }
}

- (void)hiddenActivityView {
    
    self.activity.hidden = YES;
    self.contentInset = UIEdgeInsetsMake(0, 0, 0, 0);
}

//下拉获取数据源
- (void)applyForDataSource {
    [self insertSource:self.results.count];
    [self hiddenActivityView];
}

//加载更多数据后，要插入数组中
- (void)insertSource:(NSInteger)start {
    
    dispatch_async(dispatch_get_main_queue(), ^{
        
        NSMutableArray *olderMsgs = [self.chatProtocol queryChatList:self.rcChat.friendid curCount:start];
        NSInteger newInsertCount = [olderMsgs count];
        
        if (newInsertCount > 0) {
            @synchronized(self){
                NSRange indexs;
                indexs.location=0;
                indexs.length=newInsertCount;
                [self.results insertObjects:olderMsgs atIndexes:[NSIndexSet indexSetWithIndexesInRange:indexs]];
                
                [self reloadData];
                
                [self scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:newInsertCount inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
            }
        }
        [self hiddenActivityView];
        [self.heightArray removeAllObjects];
    });
}

//插入最后一条数据
- (void)insertLastMessage {

    dispatch_async(dispatch_get_main_queue(), ^{
#warning 把最后一条数据插进来,再写吧
//        [self.results addObject:[self.chatProtocol lassMessageFromID]];
        [self reloadTable:YES];
    });
}

- (void)reloadTable:(BOOL)animated {
    [self.heightArray removeAllObjects];
    [self reloadData];
    [self downBottom:animated];
}

//定位到具体位置
- (void)locateToSpecificPosition:(NSInteger)location {
    
    [self.heightArray removeAllObjects];
    [self reloadData];
    
    NSIndexPath *scrollIndexPath = [NSIndexPath indexPathForRow:location inSection:0];
    [self scrollToRowAtIndexPath:scrollIndexPath atScrollPosition:UITableViewScrollPositionTop animated:NO];
}

//数据降到最底部
- (void)downBottom:(BOOL)animated {

    CGFloat tableViewH = self.frame.size.height;
    CGSize contentSize=self.contentSize;
    if (contentSize.height>tableViewH)
    {
        [self setContentOffset:CGPointMake(0, contentSize.height - tableViewH) animated:animated];
    }

}

@end
